<template>
  <card title="注册" width="550px">
    <el-form ref="register" :rules="checkRules" :model="registerForm" label-width="80px" label-position="left">
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="registerForm.email" placeholder="用户名/邮箱" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirm">
        <el-input type="password" v-model="registerForm.confirm" placeholder="请确认密码" />
      </el-form-item>

      <el-form-item label="验证码" prop="verify_code">
        <el-input placeholder="请输入邮件验证码" v-model="registerForm.verify_code" maxlength="6">
          <template slot="append">
            <el-button @click="sendEmailVcode">
              <span>发送邮件验证码</span>
              <span v-show="isCountDowning">({{ seconds }})</span>
            </el-button>
          </template>
        </el-input>
      </el-form-item>

      <div class="flex justify-center">
        <el-button type="primary" @click="register" style="width: 150px; margin-bottom: 10px">注册</el-button>
      </div>
      <div class="flex justify-center">
        <el-button type="text" @click="$router.push({ name: 'login' })">已有账号? 去登录</el-button>
      </div>
    </el-form>
  </card>
</template>

<script>
import card from "@/components/card/index.vue";
import regex from "@/utils/regex";
import { register, sendVerifyCode } from "@/api/user";

export default {
  name: "register",
  components: { card },
  data() {
    // 检查确认密码:
    return {
      timer: null,
      seconds: 60,
      isCountDowning: false, // 是否正在倒计时
      registerForm: {
        email: "",
        password: "",
        confirm: "",
        verify_code: "",
      },
      checkRules: {
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" },
          { pattern: regex.email, message: "邮箱格式有误", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { pattern: regex.password, message: "密码格式有误,至少6位字符", trigger: "blur" },
        ],
        confirm: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          {
            validator: (rule, val, callback) => {
              this.registerForm.password === val ? callback() : callback(new Error("两次密码不一致"));
            },
            trigger: "blur",
          },
        ],
        verify_code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 开启倒计时
    startTimer() {
      this.isCountDowning = true;
      this.timer && clearInterval(this.timer);
      this.timer = setInterval(() => {
        if (this.seconds === 0) {
          clearInterval(this.timer);
          this.isCountDowning = false;
          return;
        }
        this.seconds--;
      }, 1000);
    },

    // 发送邮件验证码
    async sendEmailVcode() {
      if (this.isCountDowning) {
        return;
      }
      const { email } = this.registerForm;
      if (!regex.email.test(email)) {
        this.$message.error("请正确填写邮箱地址!");
        return;
      }
      const res = await sendVerifyCode({ email });
      if (res.success) {
        this.startTimer();
        this.$message.success("验证码发送成功, 请前往邮箱查收");
        return;
      }
      this.$message.error("邮件发送失败:" + res.msg);
    },

    // 处理登录: 先验证数据是否通过检测规则
    register() {
      this.$refs.register.validate(async (isPassed) => {
        if (!isPassed) {
          this.$message.error("数据格式有误,请检查后再次尝试");
          return;
        }
        const res = await register(this.registerForm);
        if (res.success) {
          this.$message.success("登录成功");
          this.$store.commit("user/login", res.data);
          this.$router.push({ name: "home" });
          return;
        }
        this.$message.error("登录失败:" + res.msg);
      });
    },
  },
};
</script>
